package cn.com.demo.cms;

import org.bouncycastle.cms.*;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.Iterator;

public class KeyEnvelopedDataExample {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("DESEDE", "BC");
        SecretKey key = keyGen.generateKey();

        //set up the generator
        CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
        byte[] keyId = new byte[]{1, 2, 3, 4, 5};
        gen.addKEKRecipient(key, keyId);

        //create the enveloped-data object
        CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

        CMSEnvelopedData enveloped = gen.generate(
                data, CMSEnvelopedDataGenerator.AES128_CBC, "BC");

        //re-create
        enveloped = new CMSEnvelopedData(enveloped.getEncoded());

        //look for our recipient
        RecipientInformationStore recipients = enveloped.getRecipientInfos();

        Iterator i = recipients.getRecipients().iterator();
        if (i.hasNext()) {
            RecipientInformation recipient = (RecipientInformation) i.next();

            if (recipient != null) {
                //decrypt the data
                byte[] decData = recipient.getContent(key, "BC");

                // compare recovered data to the original data
                if (Arrays.equals(decData, (byte[]) data.getContent())) {
                    System.out.println("data recovery succeeded");
                } else {
                    System.out.println("data recovery failed");
                }
            } else {
                System.out.println("could not find a matching recipient");
            }
        }
    }

}
